package com.yimils.core.sys.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yimils.core.sys.entity.ResourceEntity;
import com.yimils.core.sys.entity.RoleEntity;
import com.yimils.core.sys.entity.RoleResourceEntity;
import com.yimils.core.sys.mapper.RoleMapper;
import com.yimils.core.sys.po.UserRoleDo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service("roleService")
public class RoleServiceImpl extends ServiceImpl<RoleMapper, RoleEntity> implements RoleService {
    @Resource(name = "resourceService")
    private ResourceService resourceService;

    @Resource(name = "roleResourceService")
    private RoleResourceService roleResourceService;

    @Resource(name = "userRoleService")
    private UserRoleService userRoleService;

    @Override
    public List<RoleEntity> getRoleList(Integer type) {
        QueryWrapper<RoleEntity> qw = new QueryWrapper<>();
        qw.lambda().eq(RoleEntity::getType, type);
        if (type != null) {
            return list(qw);
        }
        return list();
    }

    @Override
    public List<RoleEntity> getRolesByType(Integer type) {
        QueryWrapper<RoleEntity> qw = new QueryWrapper<>();
        qw.lambda().eq(RoleEntity::getType, type);
        return list(qw);
    }

    @Transactional
    @Override
    public boolean createRole(RoleEntity role) {
        if (save(role)) {
            List<ResourceEntity> resources = resourceService.list();
            List<RoleResourceEntity> roleResources = new ArrayList<>();
            for (ResourceEntity resource : resources) {
                RoleResourceEntity roleResourceEntity = new RoleResourceEntity();
                roleResourceEntity.setRoleId(role.getId());
                roleResourceEntity.setResourceId(resource.getId());
                roleResourceEntity.setActive(0);
                roleResources.add(roleResourceEntity);
            }
            return roleResourceService.saveBatch(roleResources);
        }
        return false;
    }

    @Transactional
    @Override
    public boolean deleteRole(Long id) {
        if (removeById(id)) {
            QueryWrapper<RoleResourceEntity> qw = new QueryWrapper<>();
            qw.lambda().eq(RoleResourceEntity::getRoleId, id);
            return roleResourceService.remove(qw);
        }
        return false;
    }

    @Override
    public RoleEntity getRoleByUserId(Long userId) {
        QueryWrapper<RoleEntity> qw = new QueryWrapper<>();
        Long roleId = userRoleService.getHighestRoleId(userId);
        qw.lambda().eq(RoleEntity::getId, roleId);
        return getOne(qw);
    }
}
